<template>
    <div class="main">
       <el-form class="form" :model="form" ref="loginForm" :rules="rules" label-width="120px">
           <el-form-item label="用户名" prop="userName">
               <el-input v-model="form.userName" />
           </el-form-item>
           <el-form-item label="密码" prop="passWord">
               <el-input v-model="form.passWord" type="password" @keyup.enter="onSubmit()" />
           </el-form-item>
           <el-form-item>
               <el-button type="primary" @click="onSubmit(loginForm)">Submit</el-button>
               <el-button @click="reset(loginForm)">Reset</el-button>
           </el-form-item>
       </el-form>
   </div>
   
</template>
<script setup lang="ts">
import { reactive,ref} from 'vue';
import { ElMessage,FormInstance, FormRules } from 'element-plus';
import store from '../../store/index'
import router from '../../router'
import { getToken } from '../../http'
 const form = reactive({
     userName:"",  
     passWord:""
 })
const loginForm = ref<FormInstance>()
const rules = reactive<FormRules>({
    userName:[{
        required: true,
        message: '请输入用户名',
        trigger: 'blur'
    }],
    passWord:[{
        required: true,
        message: '请输入密码',
        trigger: 'blur'
    }]

})
 const onSubmit =async (loginForm: FormInstance | undefined) => {
    if(!loginForm) return

   await loginForm.validate( async(valid:boolean,fields:any) => {
        if (valid) {
            let token:string =await getToken(form) as any as string
            if (token!=null){
                ElMessage.success('登录成功')
                store().$patch((state)=>{
                    state.Token=token ,
                    //重新登录之后无感刷新token次数
                    state.RefreshTokenNum=0
                }
                )
            router.push(
                {path:'/desktop'}
            )
            }
            
        } else {
            ElMessage.error('验证失败')
            console.log(fields)
        }
    });
 }
 const reset = (loginForm: FormInstance | undefined) => {
    if(!loginForm) return
    loginForm.resetFields()
 }
</script>
<style lang="scss" scoped>
.main {
    background-image:url('/public/bg.png');
    height:100vh;
    padding-top: 20%;
}
.form {
    width: 30%;
    margin: 0px auto;
}
</style>